#!/usr/bin/env python3
"""
管理员用户验证脚本
检查并创建默认管理员账户
"""

import sys
from pathlib import Path
from typing import Any
from collections.abc import Generator

# 将项目根目录添加到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from app.models.user import User
from app.core.database import Session

# 定义数据库会话类型
class MockDBSession:
    def query(self, model: type[User]):
        return self
    
    def filter(self, condition: Any):
        return self
    
    def all(self) -> list[User]:
        return []

# 数据库可用性标志 - 使用小写避免常量重定义
_db_available: bool = False

# 尝试导入数据库模块
try:
    from app.core.database import get_db
    _db_available = True
except ImportError:
    # 如果无法导入，使用模拟函数
    def get_db() -> Generator[Session, None, None]:
        db = Session()
        try:
            yield db
        finally:
            db.close()

def verify_admin_users() -> tuple[bool, list[dict[str, Any]]]:
    """
    验证管理员用户是否存在
    
    Returns:
        tuple[bool, list[dict[str, Any]]]: (是否需要创建管理员, 管理员列表)
    """
    # 获取数据库会话
    if _db_available:
        db_generator = get_db()
        db = next(db_generator)
        
        # 检查现有管理员用户
        admin_users: list[User] = list(db.query(User).filter(User.is_admin == True).all())
        
        if not admin_users:
            print("未找到管理员用户，需要创建默认管理员账户")
            return True, []
        
        print(f"找到 {len(admin_users)} 个管理员用户:")
        admin_list: list[dict[str, Any]] = []
        for user in admin_users:
            admin_info: dict[str, Any] = {
                "id": int(getattr(user, 'id', 0)),
                "username": str(getattr(user, 'username', '')),
                "email": str(getattr(user, 'email', '')) if getattr(user, 'email', None) else "",
                "full_name": str(getattr(user, 'full_name', '')) if getattr(user, 'full_name', None) else "",
                "is_active": bool(getattr(user, 'is_active', False)),
                "is_admin": bool(getattr(user, 'is_admin', False))
            }
            admin_list.append(admin_info)
            print(f"  - {admin_info['username']} ({admin_info['email']})")
        
        return False, admin_list
    else:
        print("数据库不可用，无法验证管理员用户")
        return True, []


if __name__ == "__main__":
    try:
        need_create, admins = verify_admin_users()
        if need_create:
            print("请运行 check_admin_users.py 脚本来创建管理员用户")
            sys.exit(1)
        else:
            print("管理员用户验证完成")
            sys.exit(0)
    except Exception as e:
        print(f"验证管理员用户时出错: {e}")
        sys.exit(1)